﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Reflection;
using TDB.Communication;
using TeamDev.SDK;
using System.ServiceModel.Description;
using TDB.DBInternals;

namespace TDB.Service
{
  public partial class Server : ServiceBase
  {

    private ServiceHost inputservicehost = null;
    private ServiceHost outputservicehost = null;
    private ServiceHost administrationservicehost = null;

    public Server()
    {
      var version = Assembly.GetExecutingAssembly().GetName().Version;
      InitializeComponent();
      ServiceName = string.Format("TDB Server {0}.{1} - rev: {2}", version.Major, version.Minor, version.Revision);


      EventLogWriter.EventDefaultSourceName = "TDB Server";
    }

    public void Start()
    {
      OnStart(null);
    }

    protected override void OnStart(string[] args)
    {
      try
      {
        if (inputservicehost != null) inputservicehost.Close();
        if (outputservicehost != null) outputservicehost.Close();
        if (administrationservicehost != null) administrationservicehost.Close();

        inputservicehost = new ServiceHost(new CommandService());
        administrationservicehost = new ServiceHost(new AdministrationService());
        outputservicehost = new ServiceHost(typeof(QueryService));

        ContractDescription cd = inputservicehost.Description.Endpoints[0].Contract;
        foreach (var op in cd.Operations)
        {
          DataContractSerializerOperationBehavior serializerBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();
          if (serializerBehavior != null)
            serializerBehavior.DataContractResolver = new TypeResolver();
        }


        administrationservicehost.Open();
        outputservicehost.Open();
        inputservicehost.Open();
      }
      catch (Exception ex)
      {
        EventLogWriter.LogException(ex);
      }
    }

    protected override void OnStop()
    {
      if (inputservicehost != null) { inputservicehost.Close(); inputservicehost = null; }
      if (outputservicehost != null) { outputservicehost.Close(); outputservicehost = null; }
      if (administrationservicehost != null) { administrationservicehost.Close(); administrationservicehost = null; }
    }
  }
}
